<template>
  <div class="ai-review">
    <header class="header">
      <div class="header-left">
        <el-button type="text" @click="$router.back()"><el-icon><ArrowLeft /></el-icon></el-button>
        <h1>AI诊断复核</h1>
      </div>
      <div class="header-right">
        <el-dropdown>
          <span class="user-info">
            <el-avatar :size="32" :src="userStore.currentUser?.avatar"></el-avatar>
            <span>{{ userStore.currentUser?.name || '医生用户' }}</span>
            <el-icon class="el-icon--right"><ArrowDown /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item @click="handleLogout">退出登录</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </header>
    
    <div class="content">
      <!-- 筛选和搜索 -->
      <div class="filter-section">
        <div class="filter-left">
          <el-select v-model="filterStatus" placeholder="状态" class="filter-select">
            <el-option label="全部" value=""></el-option>
            <el-option label="待复核" value="pending"></el-option>
            <el-option label="已完成" value="completed"></el-option>
          </el-select>
          <el-select v-model="filterExamType" placeholder="检查类型" class="filter-select">
            <el-option label="全部" value=""></el-option>
            <el-option label="CT" value="CT"></el-option>
            <el-option label="MRI" value="MRI"></el-option>
            <el-option label="X光" value="X光"></el-option>
            <el-option label="超声" value="超声"></el-option>
          </el-select>
        </div>
        <div class="filter-right">
          <el-input
            v-model="searchKeyword"
            placeholder="搜索患者姓名或ID"
            prefix-icon="Search"
            class="search-input"
          ></el-input>
        </div>
      </div>
      
      <!-- 病例列表 -->
      <el-card class="case-list-card">
        <template #header>
          <div class="card-header">
            <span>待复核病例列表</span>
            <el-badge :value="filteredCases.length" type="info" class="case-count"></el-badge>
          </div>
        </template>

        <el-table
          v-loading="loading"
          :data="filteredCases"
          style="width: 100%"
          @row-click="handleCaseClick"
          row-class-name="case-row"
        >
          <el-table-column prop="id" label="病例ID" width="100"></el-table-column>
          <el-table-column prop="patient.name" label="患者姓名" width="120">
            <template #default="scope">
              <div>{{ scope.row.patient.name }}</div>
              <div class="patient-id">{{ scope.row.patient.id }}</div>
            </template>
          </el-table-column>
          <el-table-column prop="patient.age" label="年龄" width="80"></el-table-column>
          <el-table-column prop="patient.gender" label="性别" width="80"></el-table-column>
          <el-table-column prop="examType" label="检查类型" width="100"></el-table-column>
          <el-table-column prop="uploadTime" label="上传时间" width="180">
            <template #default="scope">
              {{ formatDateTime(scope.row.uploadTime) }}
            </template>
          </el-table-column>
          <el-table-column prop="aiStatus" label="AI状态" width="120">
            <template #default="scope">
              <el-tag :type="getAiStatusType(scope.row.aiStatus)">
                {{ getAiStatusText(scope.row.aiStatus) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="status" label="复核状态" width="100">
            <template #default="scope">
              <el-tag :type="getStatusType(scope.row.status)">
                {{ scope.row.status === 'pending' ? '待复核' : '已完成' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="120">
            <template #default="scope">
              <el-button
                type="primary"
                size="small"
                @click.stop="handleReview(scope.row)"
                :disabled="scope.row.status === 'completed'"
              >
                复核
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="filteredCases.length"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          ></el-pagination>
        </div>
      </el-card>
      
      <!-- 复核详情对话框 -->
      <el-dialog
        v-model="reviewDialogVisible"
        :title="`病例复核 - 患者：${selectedCase?.patient?.name || ''}`"
        width="90%"
        height="80vh"
        :fullscreen="isMobile"
      >
        <div class="review-dialog-content" v-if="selectedCase">
          <!-- 患者信息 -->
          <div class="patient-info-panel">
            <h3>患者信息</h3>
            <div class="info-grid">
              <div class="info-item">
                <label>患者姓名：</label>
                <span>{{ selectedCase.patient.name }}</span>
              </div>
              <div class="info-item">
                <label>患者ID：</label>
                <span>{{ selectedCase.patient.id }}</span>
              </div>
              <div class="info-item">
                <label>性别：</label>
                <span>{{ selectedCase.patient.gender }}</span>
              </div>
              <div class="info-item">
                <label>年龄：</label>
                <span>{{ selectedCase.patient.age }}岁</span>
              </div>
              <div class="info-item">
                <label>检查类型：</label>
                <span>{{ selectedCase.examType }}</span>
              </div>
              <div class="info-item">
                <label>上传时间：</label>
                <span>{{ formatDateTime(selectedCase.uploadTime) }}</span>
              </div>
            </div>
          </div>

          <!-- 影像查看器 -->
          <div class="image-viewer">
            <h3>影像查看</h3>
            <div class="image-container">
              <div
                v-for="(image, index) in selectedCase.images"
                :key="index"
                class="image-item"
                :class="{ active: currentImageIndex === index }"
                @click="currentImageIndex = index"
              >
                <el-image
                  :src="image.url"
                  :preview-src-list="selectedCase.images.map(img => img.url)"
                  fit="contain"
                ></el-image>
              </div>
            </div>
            <!-- 缩略图导航 -->
            <div class="thumbnails" v-if="selectedCase.images.length > 1">
              <div
                v-for="(image, index) in selectedCase.images"
                :key="index"
                class="thumbnail-item"
                :class="{ active: currentImageIndex === index }"
                @click="currentImageIndex = index"
              >
                <el-image :src="image.url" fit="cover"></el-image>
              </div>
            </div>
          </div>

          <!-- AI诊断结果 -->
          <div class="ai-result">
            <h3>AI诊断结果</h3>
            <el-timeline>
              <el-timeline-item
                v-for="(step, index) in selectedCase.aiAnalysis.steps"
                :key="index"
                :timestamp="formatTime(step.timestamp)"
              >
                <h4>{{ step.title }}</h4>
                <p>{{ step.description }}</p>
                <div v-if="step.findings && step.findings.length > 0" class="ai-findings">
                  <h5>发现：</h5>
                  <ul>
                    <li v-for="(finding, i) in step.findings" :key="i">
                      {{ finding.description }}
                      <span class="confidence" v-if="finding.confidence">
                        (置信度: {{ finding.confidence }}%)
                      </span>
                    </li>
                  </ul>
                </div>
              </el-timeline-item>
            </el-timeline>
            <div class="ai-conclusion">
              <h4>AI结论</h4>
              <p>{{ selectedCase.aiAnalysis.conclusion }}</p>
              <div v-if="selectedCase.aiAnalysis.result" class="ai-result-summary">
                <div class="result-item">
                  <span class="label">分析结果：</span>
                  <span class="value">{{ selectedCase.aiAnalysis.result }}</span>
                </div>
                <div v-if="selectedCase.aiAnalysis.confidence" class="result-item">
                  <span class="label">置信度：</span>
                  <span class="value">{{ (selectedCase.aiAnalysis.confidence * 100).toFixed(1) }}%</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 医生复核表单 -->
          <div class="review-form">
            <h3>医生复核</h3>
            <el-form :model="reviewForm" label-width="120px">
              <el-form-item label="诊断意见">
                <el-radio-group v-model="reviewForm.diagnosisAgree">
                  <el-radio label="agree">同意AI诊断</el-radio>
                  <el-radio label="partially">部分同意</el-radio>
                  <el-radio label="disagree">不同意</el-radio>
                </el-radio-group>
              </el-form-item>
              <el-form-item label="复核说明">
                <el-input
                  v-model="reviewForm.reviewNotes"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入您的复核意见和说明"
                ></el-input>
              </el-form-item>
              <el-form-item label="最终诊断">
                <el-input
                  v-model="reviewForm.finalDiagnosis"
                  type="textarea"
                  :rows="4"
                  placeholder="请输入最终诊断结果"
                ></el-input>
              </el-form-item>
              <el-form-item label="建议">
                <el-input
                  v-model="reviewForm.recommendations"
                  type="textarea"
                  :rows="2"
                  placeholder="请输入后续建议"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-checkbox v-model="reviewForm.approveReport">同意AI分析，生成最终诊断报告</el-checkbox>
              </el-form-item>
            </el-form>
          </div>
        </div>
        <template #footer>
          <div class="review-footer">
            <el-button @click="reviewDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitReview" :loading="submitting">
              提交复核{{ reviewForm.approveReport ? '并生成报告' : '' }}
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useUserStore } from '../stores/user';
import { ArrowLeft, ArrowDown, Search } from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

export default {
  name: 'AiReview',
  components: { ArrowLeft, ArrowDown, Search },
  setup() {
    const router = useRouter();
    const userStore = useUserStore();

    const loading = ref(false);
    const cases = ref([]);
    const selectedCase = ref(null);
    const reviewDialogVisible = ref(false);
    const currentImageIndex = ref(0);
    const submitting = ref(false);

    const currentPage = ref(1);
    const pageSize = ref(10);

    const filterStatus = ref('');
    const filterExamType = ref('');
    const searchKeyword = ref('');

    const isMobile = computed(() => window.innerWidth < 768);

    const filteredCases = computed(() => {
      return cases.value.filter(item => {
        if (filterStatus.value && item.status !== filterStatus.value) return false;
        if (filterExamType.value && item.examType !== filterExamType.value) return false;
        if (searchKeyword.value) {
          const kw = searchKeyword.value.toLowerCase();
          return String(item.patient.name || '').toLowerCase().includes(kw) || String(item.patient.id || '').includes(kw);
        }
        return true;
      });
    });

    const fetchJson = async (url) => {
      const resp = await fetch(url);
      if (!resp.ok) throw new Error(`HTTP ${resp.status}`);
      return await resp.json();
    };

    const loadCases = async () => {
      if (!userStore.currentUser?.id) return;
      loading.value = true;
      try {
        // 获取AI报告数据，这是我们需要复核的内容
        const reports = await fetchJson('/api/ai-reports');
        const patients = await fetchJson('/api/patients');
        const images = await fetchJson('/api/images');
        
        const patientMap = new Map(patients.map(p => [p.id, p]));
        const imageMap = new Map(images.map(img => [img.id, img]));
        
        // 过滤出待复核的报告
        cases.value = reports
          .filter(report => report.reviewStatus !== '已复核')
          .map(report => {
            const p = patientMap.get(report.patientId) || {};
            const img = imageMap.get(report.imageId) || {};
            
            return {
              id: report.id,
              patient: { 
                name: p.name || `患者${report.patientId}`, 
                id: String(report.patientId), 
                age: p.age || '', 
                gender: p.gender || '' 
              },
              examType: '医学影像',
              uploadTime: new Date(report.analysisTime).getTime(),
              aiStatus: 'completed',
              status: report.reviewStatus === '已复核' ? 'completed' : 'pending',
              images: img.filename ? [ { url: `/uploads/${img.filename}` } ] : [],
              aiAnalysis: {
                steps: [],
                conclusion: report.details,
                result: report.analysisResult,
                confidence: report.confidence
              },
              reportId: report.id
            };
          });
      } catch (e) {
        ElMessage.error('加载复核数据失败');
      } finally {
        loading.value = false;
      }
    };

    const formatDateTime = (ts) => new Date(ts).toLocaleString();
    const formatTime = (ts) => new Date(ts).toLocaleTimeString();
    const getAiStatusType = (s) => (s === 'completed' ? 'success' : s === 'processing' ? 'warning' : 'info');
    const getAiStatusText = (s) => (s === 'completed' ? '已完成' : s === 'processing' ? '分析中' : '未知');
    const getStatusType = (s) => (s === 'pending' ? 'warning' : 'success');

    const handleCaseClick = () => {};
    const handleReview = (row) => {
      selectedCase.value = row;
      currentImageIndex.value = 0;
      reviewForm.value = { diagnosisAgree: 'agree', reviewNotes: '', finalDiagnosis: row.aiAnalysis.conclusion, recommendations: '' };
      reviewDialogVisible.value = true;
    };
    const submitReview = async () => {
      if (!reviewForm.value.finalDiagnosis && !reviewForm.value.reviewNotes) {
        ElMessage.warning('请填写复核意见或最终诊断结果');
        return;
      }
      
      submitting.value = true;
      try {
        // 构建医生评语，组合诊断意见、复核说明和建议
        let doctorComment = '';
        
        if (reviewForm.value.diagnosisAgree === 'agree') {
          doctorComment += '同意AI诊断，';
        } else if (reviewForm.value.diagnosisAgree === 'partially') {
          doctorComment += '部分同意AI诊断，';
        } else {
          doctorComment += '不同意AI诊断，';
        }
        
        if (reviewForm.value.reviewNotes) {
          doctorComment += `复核说明：${reviewForm.value.reviewNotes}。`;
        }
        
        if (reviewForm.value.finalDiagnosis) {
          doctorComment += `最终诊断：${reviewForm.value.finalDiagnosis}。`;
        }
        
        if (reviewForm.value.recommendations) {
          doctorComment += `建议：${reviewForm.value.recommendations}。`;
        }
        
        // 调用后端API提交复核结果
        const response = await fetch(`/api/ai-reports/${selectedCase.value.reportId}/review`, {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            doctorComment,
            approved: reviewForm.value.approveReport
          })
        });
        
        if (!response.ok) {
          throw new Error('提交失败');
        }
        
        ElMessage.success('复核提交成功！' + (reviewForm.value.approveReport ? '诊断报告已生成。' : '将不会生成最终报告。'));
        reviewDialogVisible.value = false;
        
        // 重新加载数据以更新列表
        await loadCases();
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error('提交失败，请重试');
      } finally {
        submitting.value = false;
      }
    };

    const handleSizeChange = (s) => { pageSize.value = s; currentPage.value = 1; };
    const handleCurrentChange = (c) => { currentPage.value = c; };
    const handleLogout = () => { userStore.logout(); router.push('/login'); };

    const reviewForm = ref({ 
      diagnosisAgree: 'agree', 
      reviewNotes: '', 
      finalDiagnosis: '', 
      recommendations: '',
      approveReport: true // 默认同意生成报告
    });

    const handleResize = () => {};

    onMounted(() => { loadCases(); window.addEventListener('resize', handleResize); });

    return {
      userStore, loading, cases, selectedCase, reviewDialogVisible, currentImageIndex, submitting,
      currentPage, pageSize, filterStatus, filterExamType, searchKeyword, filteredCases, isMobile, reviewForm,
      formatDateTime, formatTime, getAiStatusType, getAiStatusText, getStatusType, handleCaseClick, handleReview,
      submitReview, handleSizeChange, handleCurrentChange, handleLogout
    };
  },
  beforeUnmount() { window.removeEventListener('resize', this.handleResize); }
};
</script>

<style scoped>
.ai-review {
.ai-conclusion {
  margin-top: 20px;
  padding: 15px;
  background-color: #f9f9f9;
  border-radius: 4px;
}

.ai-result-summary {
  margin-top: 15px;
  padding: 10px;
  background-color: #f0f9ff;
  border-radius: 4px;
}

.ai-result-summary .result-item {
  margin-bottom: 8px;
}

.ai-result-summary .result-item:last-child {
  margin-bottom: 0;
}

.ai-result-summary .label {
  font-weight: bold;
  color: #303133;
  margin-right: 10px;
}

.ai-result-summary .value {
  color: #606266;
}

  height: 100vh;
  display: flex;
  flex-direction: column;
}

.header {
  display: flex;
  align-items: center;
  padding: 0 30px;
  height: 60px;
  background-color: white;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.header h1 {
  margin: 0;
  color: #303133;
  font-size: 20px;
}

.content {
  flex: 1;
  padding: 30px;
  background-color: #f5f7fa;
  overflow-y: auto;
}

.filter-section {
  margin-bottom: 20px;
  display: flex;
  align-items: center;
}

.reports-list {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.report-detail {
  padding: 20px 0;
}

.report-header {
  display: flex;
  justify-content: space-between;
  margin-bottom: 30px;
  padding-bottom: 20px;
  border-bottom: 1px solid #ebeef5;
}

.patient-info, .report-info {
  flex: 1;
}

.patient-info h3, .report-info h3, .image-section h3, .analysis-section h3, .review-section h3 {
  margin: 0 0 15px 0;
  color: #303133;
}

.patient-info p, .report-info p {
  margin: 8px 0;
  color: #606266;
}

.image-section {
  margin-bottom: 30px;
}

.medical-image {
  max-width: 100%;
  max-height: 400px;
  border-radius: 4px;
  border: 1px solid #ebeef5;
}

.analysis-section {
  margin-bottom: 30px;
}

.analysis-result {
  background-color: #f5f7fa;
  padding: 20px;
  border-radius: 4px;
}

.result-item {
  margin-bottom: 20px;
}

.label {
  font-weight: 500;
  color: #303133;
  margin-right: 10px;
}

.result-tag {
  font-size: 16px;
  padding: 5px 15px;
}

.confidence-bar {
  width: 200px;
  display: inline-block;
  vertical-align: middle;
  margin: 0 10px;
}

.confidence-text {
  color: #606266;
}

.details-text {
  margin: 10px 0 0 0;
  color: #606266;
  line-height: 1.8;
}

@media (max-width: 768px) {
  .content {
    padding: 20px;
  }
  
  .header {
    padding: 0 20px;
  }
  
  .report-header {
    flex-direction: column;
    gap: 20px;
  }
  
  .confidence-bar {
    width: 100%;
    margin: 10px 0;
  }
}
</style>